package com.iterative.system.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.iterative.common.web.BaseController;
import com.iterative.system.entity.Permission;
import com.iterative.system.entity.Role;
import com.iterative.system.entity.RolePermission;
import com.iterative.system.entity.User;
import com.iterative.system.entity.UserRole;
import com.iterative.system.service.PermissionService;
import com.iterative.system.service.RolePermissionService;
import com.iterative.system.service.RoleService;
import com.iterative.system.service.UserRoleService;
import com.iterative.system.service.UserService;

/**
 * 
 * 初始化类
 * @author like
 *
 */
@Controller
@RequestMapping("/init")
public class InitController extends BaseController{
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RolePermissionService rolePermissionService;
	@Autowired
	private UserRoleService userRoleService;
	
	
	@RequestMapping("user")
	public void initUser(HttpServletRequest request, HttpServletResponse response){
		
		User user = new User();
		user.setLoginName("admin");
		user.setName("admin");
		user.setBirthday(new Date());
		user.setGender((short) 1);
		user.setDescription("超级管理员");
		user.setPlainPassword("admin");
		userService.save(user);
	}

	@RequestMapping("role")
	public void initRole(){
		Role role = new Role();
		role.setDescription("超级管理员");
		role.setName("admin");
		role.setRoleCode("admin");
		role.setSort(1);
		roleService.save(role);
	}
	
	@RequestMapping("ur")
	public void userRole(){
		User user = userService.getUser("admin");
		Role role = roleService.getRoleByName("admin");
		UserRole ur = new UserRole();
		ur.setRoleId(role.getId());
		ur.setUserId(user.getId());
		userRoleService.save(ur);
	}
	
	@RequestMapping("rp")
	public void initRole_Permission(){
		Role role = roleService.getRoleByName("admin");
		List<Permission> permissions = permissionService.getAll();
		for (Permission permission : permissions) {
			RolePermission rp = new RolePermission();
			rp.setRoleId(role.getId());
			rp.setPermissionId(permission.getId());
			rolePermissionService.save(rp);
		}
	}
	
}
